package com.suns.sharephoto.controller;

import com.suns.sharephoto.common.Result;
import com.suns.sharephoto.entity.Photo;
import com.suns.sharephoto.entity.User;
import com.suns.sharephoto.mapper.PhotoMapper;
import com.suns.sharephoto.mapper.UserMapper;
import com.suns.sharephoto.service.UserService;
import com.suns.sharephoto.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/photo")
@CrossOrigin
@RequiredArgsConstructor
public class PhotoController {

    private final PhotoMapper photoMapper;
    private final JwtUtil jwtUtil;
    private final UserMapper userMapper;

    @Value("${photo.upload.dir}")
    private String uploadDir;
    @Autowired
    private UserService userService;

    /**
     * 获取轮播图数据（点赞数最多的5张图片）
     */
    @GetMapping("/slides")
    public Result<?> getSlides() {
        try {
            List<Photo> slides = photoMapper.findSlides();
            return Result.success(slides);
        } catch (Exception e) {
            log.error("获取轮播图失败", e);
            return Result.error("获取轮播图失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取图片列表（不包括轮播图中的图片）
     */
    @GetMapping("/list")
    public Result<?> getPhotoList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        try {
            int offset = (page - 1) * size;
            List<Photo> photos = photoMapper.findByPage(offset, size);
            int total = photoMapper.count();

            Map<String, Object> data = Map.of(
                    "list", photos,
                    "total", total,
                    "page", page,
                    "size", size,
                    "hasMore", (offset + photos.size()) < total
            );

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取图片列表失败", e);
            return Result.error("获取图片列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/like/{id}")
    public Result<?> likePhoto(@PathVariable Integer id) {
        try {
            Photo photo = photoMapper.findById(id);
            if (photo == null) {
                return Result.error("图片不存在");
            }

            // 增加点赞数
            photoMapper.updateLikes(id, photo.getLikes() + 1);
            return Result.success(null);
        } catch (Exception e) {
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    @PostMapping("/upload")
    @ResponseBody
    public Result<?> uploadPhoto(
            @RequestParam("file") MultipartFile file,
            @RequestHeader("Authorization") String token
    ) {
        try {
            // 验证token
            String tokenValue = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(tokenValue)) {
                return Result.error("无效的token");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }

            // 获取当前用户ID
            Integer userId = jwtUtil.getUserIdFromToken(tokenValue);

            // 确保上传目录存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filepath = Paths.get(uploadDir, filename);
            Files.write(filepath, file.getBytes());

            // 保存图片信息到数据库
            Photo photo = new Photo();
            photo.setUserId(userId);
            photo.setImagePath("/uploads/" + filename);
            photo.setLikes(0);
            photoMapper.insert(photo);

            // 返回完整的photo对象
            photo = photoMapper.findById(photo.getId());

            // 确保返回的数据不为null
            if (photo == null) {
                throw new RuntimeException("保存图片信息失败");
            }

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("id", photo.getId());
            responseData.put("userId", photo.getUserId());
            responseData.put("imagePath", photo.getImagePath());
            responseData.put("likes", photo.getLikes());
            responseData.put("uploadTime", photo.getUploadTime());

            if (photo.getUser() != null) {
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", photo.getUser().getId());
                userInfo.put("nickname", photo.getUser().getNickname());
                userInfo.put("avatarUrl", photo.getUser().getAvatarUrl());
                responseData.put("user", userInfo);
            }

            log.info("上传成功: {}", responseData);
            return Result.success(responseData);

        } catch (Exception e) {
            log.error("上传失败", e);
            return Result.error("上传失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{photoId}")
    public Result deletePhoto(
            @PathVariable Integer photoId,
            @RequestAttribute Integer userId) {
        userService.deletePhoto(photoId, userId);
        return Result.success("删除成功");
    }

    @GetMapping("/stats")
    public Result<?> getPhotoStats(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取用户ID
            String tokenValue = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(tokenValue)) {
                return Result.error("无效的token");
            }
            Integer userId = jwtUtil.getUserIdFromToken(tokenValue);

            // 获取用户信息
            User user = userMapper.findById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 获取统计数据
            Integer totalPhotos = photoMapper.countUserPhotos(userId);
            Integer totalLikes = photoMapper.countUserTotalLikes(userId);

            // 构建返回数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("openid", user.getOpenid());
            stats.put("totalPhotos", totalPhotos);
            stats.put("totalLikes", totalLikes);

            return Result.success(stats);
        } catch (Exception e) {
        }
        return null;
    }
}